<?php

namespace App\Models;

use App\Handlers\KeysHandler;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;

class Banner extends Model
{
    use SoftDeletes;

    protected $fillable = ['title', 'image', 'jump', 'route', 'show', 'sort', 'locale'];

    //位置
    const HOME = 0; //首页
    const WELFARE_GOODS = 1; //福利商品
    const LOCATION = [
        self::HOME => '首页',
        self::WELFARE_GOODS => '福利商品'
    ];

    //跳转页面
    const NO = 0;//不跳转

    const JUMP_MAP = [
        self::NO => '不跳转',
    ];

    //客户端路由
    const CLIENT_ROUTE_MAP = [
        self::NO => '',
    ];


    public function getLocaleAttribute($value)
    {
        return explode(',', $value);
    }

    public function setLocaleAttribute($value)
    {
        $this->attributes['locale'] = implode(',', $value);
    }

    /**
     * 获取banner图 (根据语言包跟位置 缓存三分钟)
     * @param $location
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getBanner($location, $limit)
    {
        $locale = App::getLocale();
        return Cache::remember(sprintf(KeysHandler::BANNER, $locale, $location), now()->addMinutes(5), function () use ($locale, $location, $limit) {
            return self::query()
                ->where('locale', 'like', "%$locale%")
                ->where('location', $location)
                ->where('show', 1)
                ->when($limit != 0, function ($query) use ($limit) {
                    $query->limit($limit);
                })
                ->orderBy('sort')
                ->select('id', 'title', 'image', 'route')
                ->get();
        });
    }


    //从缓存中获取所有数据
    public static function getAllBannerByCache()
    {
        return Cache::rememberForever(KeysHandler::BANNER, function () {
            return self::all();
        });
    }
}
